package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.commo.PageResult;
import com.itheima.commo.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.AddressBook;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.entity.User;
import com.itheima.mapper.OrdersDetailMapper;
import com.itheima.mapper.OrdersMapper;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单业务层接口类
 */
@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    //订单详情表业务接口
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrdersDetailMapper ordersDetailMapper;

    /**
     * 下单
     *
     * @param orders
     * @param session
     */
    @Override
    public void add(Orders orders, HttpSession session) {
        log.debug("**下单**",orders.toString());
        User user = (User) session.getAttribute("user");
        //1补全ordes表中的数据
        //1.1获取唯一的订单号 设置orders表中的number字段
        orders.setNumber(IdWorker.getId() + "");
        //1.2下单设置 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(3);
        //1.3 下单用户id userId 可以从ThreadLocal中获取当前用户id
        orders.setUserId(user.getId());
        //1.4 addressBookId payMethod amount remark(页面上传入的数据)
        //1.5 orderTime 设置当前时间为下单时间
        orders.setOrderTime(LocalDateTime.now());
        //1.6 checkoutTime 设置当前时间为结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7 userName user表中name值
        orders.setUserName(user.getName());
        //1.8 phone address consignee address_book地址薄表中phone手机号  address地址  consignee收货人名字
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());//收货人手机号
        orders.setAddress(addressBook.getDetail());//收货地址
        orders.setConsignee(addressBook.getConsignee());//收货人
        log.debug("**保存订单数据**",orders.toString());
        //2 保存订单数据到orders表中
        ordersMapper.insert(orders);
        Long ordersId  = orders.getId();//订单表主键id 设置到订单详情表中orderId
        log.debug("**订单保存成功了**订单主键id为{}**",ordersId);
        //3 保存订单详情到order_detail表中
        orderDetailService.insert(ordersId);
        log.debug("**订单详情表保存成功了**");

    }

    /**
     * 订单明细
     *
     * @param page
     * @param pageSize
     */
    @Override
    public PageResult<Orders> findPage(Long page, Long pageSize) {
        Page<Orders> pj = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(pj, lqw);
        return new PageResult<>(pj.getTotal(), pj.getRecords());
    }

    /**
     * 派送订单
     *
     * @param orders
     */
    @Override
    public void update(Orders orders) {
        UpdateWrapper<Orders> ow = new UpdateWrapper<>();
        ow.eq("id", orders.getId()).set("status", orders.getStatus());
        ordersMapper.update(null, ow);
    }

    /**
     * 手机端查看历史订单
     *
     * @param page
     * @param pageSize
     */
    @Override
    public R<Page> userPage(Integer page, Integer pageSize) {
        //创建订单表分页对象
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        //设置条件
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(ordersPage, lqw);
        //创建OrdersDto分页对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //将订单表和OrdersDto copy 到 properties中
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList =  ordersList.stream().map(
                item -> {
                    Long id = item.getId();
                    OrdersDto ordersDto = new OrdersDto();
                    BeanUtils.copyProperties(item,ordersDto);

                    LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
                    lqw2.eq(OrderDetail::getOrderId, id);

                    List<OrderDetail> orderDetails = ordersDetailMapper.selectList(lqw2);
                    ordersDto.setOrderDetails(orderDetails);
                    return ordersDto;
                }
        ).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

}
